import pymysql

class DBUtil:
    conn = None
    # 连接数据库
    @classmethod
    def __get_conn(cls):
        if cls.conn is None:
            cls.conn = pymysql.connect(host="localhost", port=3306, user="root", password="1234", database="tlias",
                                       charset="utf8")
        return cls.conn
    # 关闭数据库
    @classmethod
    def __close_conn(cls):
        # 判断conn是否为空，不为空则需要关闭
        if cls.conn is not None:
            cls.conn.close()
            # 置空
            cls.conn = None

    # 查询操作
    @classmethod
    def select_one(cls,sql):
        result = None
        cursor = None
        try:
            # 获取游标
            cursor = cls.__get_conn().cursor()
            # 执行sql语句
            cursor.execute(sql)
            # 查询到的结果放回
            result = cursor.fetchone()
        except Exception as e:
            print(f"执行{sql}出现错误：{str(e)}")
            raise e
        finally:
            # 关闭游标
            cursor.close()
            # 关闭数据库
            cls.__close_conn()
            return result
    # 增删改操作
    @classmethod
    def uid_db(cls,sql):
        cursor = None
        try:
            # 获取游标
            cursor = cls.__get_conn().cursor()
            # 执行sql语句
            cursor.execute(sql)
            # 提交事务
            cls.conn.commit()
        except Exception as e:
            # 回滚操作
            cls.conn.rollback()
            print(f"执行{sql}出现错误：{str(e)}")
            raise e
        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            cls.__close_conn()






